#include "worker.h"

void Worker::run()
{
    while (m_bisstart)
    {
        QString str = parseOneMessage();
        if (!str.isEmpty())
        {
            QStringList tempList;
            for (int i = 0; i < 16; i += 2)
            {
                tempList.append(str.mid(i, 2));
            }
            if (tempList.at(0) == "5a" && tempList.at(1) == "a5")
            {
                QString value = tempList.at(5);
                double value2 = HexToInt(QStringList() << tempList.at(6) << tempList.at(7))/10.0;
                emit resultReady(value,value2);
            }
        }
        msleep(20);
    }
}

void Worker::clearData()
{
    QMutexLocker locker(&mutex);
    m_pBufferArray.clear();
}

void Worker::appendData(const QByteArray &array)
{
    QMutexLocker locker(&mutex);
    m_pBufferArray.append(array);
}

void Worker::setStart()
{
    if(!m_bisstart)
    {
        m_bisstart = true;
        start();
    }
}

void Worker::setStop()
{
    if(m_bisstart)
        m_bisstart = false;
}

QString Worker::parseOneMessage()
{
    int size = m_pBufferArray.size();
    if (size < 16)
    {
        return nullptr;
    }
    int head_index = -1;
    for (int i = 0; i < size - 1; i++)
    {
        if (m_pBufferArray[i] == '5' && m_pBufferArray[i + 1] == 'a'&& m_pBufferArray[i + 2] == 'a'&& m_pBufferArray[i + 3] == '5')
        {
            head_index = i;
            break;
        }
    }
    if (head_index == -1)
    {
        return nullptr;
    }
    m_pBufferArray = m_pBufferArray.right(size - head_index);
    //现在开始，从索引0，代表头部
    size = m_pBufferArray.size();  //重新计算缓冲区的大小
    if (size < 16)
    {
        return nullptr;
    }
    QByteArray contentByte = m_pBufferArray.mid(0, 16);

    m_pBufferArray = m_pBufferArray.right(size - 16);
    return contentByte;
}

int Worker::HexToInt(const QStringList &textList)
{
    int temp;
    QByteArray ascii_data;
    foreach(QString str, textList)
    {
        ascii_data.append(str);
    }
    bool ok;
    temp = ascii_data.toInt(&ok, 16);
    return temp;
}
